// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/exec/driver.h>

namespace kumo::pollux::exec {
    class MergeExchange;

    class MergeSource {
    public:
        static constexpr int32_t kMaxQueuedBytesUpperLimit = 32 << 20; // 32 MB.
        static constexpr int32_t kMaxQueuedBytesLowerLimit = 1 << 20; // 1 MB.

        virtual ~MergeSource() {
        }

        virtual BlockingReason next(RowVectorPtr &data, ContinueFuture *future) = 0;

        virtual BlockingReason enqueue(
            RowVectorPtr input,
            ContinueFuture *future) = 0;

        virtual void close() = 0;

        // Factory methods to create MergeSources.
        static std::shared_ptr<MergeSource> createLocalMergeSource();

        static std::shared_ptr<MergeSource> createMergeExchangeSource(
            MergeExchange *mergeExchange,
            const std::string &taskId,
            int destination,
            int64_t maxQueuedBytes,
            memory::MemoryPool *pool,
            melon::Executor *executor);
    };

    /// Coordinates data transfer between single producer and single consumer. Used
    /// to implement merge join.
    class MergeJoinSource {
    public:
        /// Called by the consumer to fetch next batch of data.
        BlockingReason next(ContinueFuture *future, RowVectorPtr *data);

        /// Called by the producer to enqueue more data or signal that no more data
        /// is coming by passing nullptr for data.
        BlockingReason enqueue(RowVectorPtr data, ContinueFuture *future);

        /// Called by the consumer to signal that it doesn't need any more data. For
        /// example, if the merge join ran out of data on the right side.
        void close();

    private:
        // Wait consumer to fetch next batch of data.
        BlockingReason waitForConsumer(ContinueFuture *future) {
            producerPromise_ = ContinuePromise("MergeJoinSource::waitForConsumer");
            *future = producerPromise_->getSemiFuture();
            return BlockingReason::kWaitForConsumer;
        }

        struct State {
            bool atEnd = false;
            RowVectorPtr data;
        };

        melon::Synchronized<State> state_;

        // Satisfied when data becomes available or the producer reports that it
        // finished producing, e.g. state_.data is not nullptr or state_.atEnd is
        // true.
        std::optional<ContinuePromise> consumerPromise_;

        // Satisfied when previously enqueued data has been consumed, e.g. state_.data
        // is nullptr.
        std::optional<ContinuePromise> producerPromise_;
    };
} // namespace kumo::pollux::exec
